import React, { useState, useEffect, useRef, Fragment } from "react";
import { Button, Input, Form, Table, Modal, Select, message, Popconfirm, TreeSelect } from "antd";
import createIcons from "@/utils/icons";
import { getAllMenu, addMenu, deleteMenu, updateMenu } from "@/api/menu";
const { Option } = Select;
const myIcons = createIcons(16);
export default () => {
    const [current, setCurrent] = useState(1);
    const currentRef = useRef(1);
    const [pageSize, setPageSize] = useState(999);
    const pageSizeRef = useRef(10);
    const [total, setTotal] = useState(10);
    const [addModalVisible, setAddModalVisible] = useState(false);
    const [allMenu, setAllMenu] = useState([]);
    const menuFormRef = useRef();
    const isAddRef = useRef(true);
    const [isAdd, setIsAdd] = useState(true);
    const editIdRef = useRef(null);
    const [columns] = useState([
        {
            title: "菜单名",
            width: 240,
            fixed: "left",
            dataIndex: "title",
        },
        {
            title: "菜单路径",
            width: 240,
            dataIndex: "path",
        },
        {
            title: "菜单图标",
            width: 240,
            dataIndex: "icon",
            render: text =>
                text ? (
                    <div>
                        {myIcons[text]}&nbsp;{text}
                    </div>
                ) : (
                    ""
                ),
        },
        {
            title: "修改时间",
            width: 200,
            dataIndex: "updateTime",
            render: text => new Date(text).toLocaleString(),
        },
        {
            title: "操作",
            width: 200,
            fixed: "right",
            dataIndex: "operation",
            render: (text, { title, _id, path, icon }) => (
                <div className="operation-wrap">
                    <Button
                        type="primary"
                        onClick={() => {
                            isAddRef.current = false;
                            setIsAdd(false);
                            setAddModalVisible(true);
                            editIdRef.current = _id;
                            setTimeout(() => {
                                menuFormRef.current.setFieldsValue({ title, path, icon });
                            });
                        }}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title={`确定删除${title}吗？`}
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => {
                            deleteMenu({ _id }).then(res => {
                                if (res.code === 200) {
                                    getAllMenu_com();
                                    message.success("删除成功");
                                } else {
                                    message.warn(res.message);
                                }
                            });
                        }}
                    >
                        <Button danger>删除</Button>
                    </Popconfirm>
                </div>
            ),
        },
    ]);
    useEffect(() => {
        getAllMenu_com();
    }, []);
    const getAllMenu_com = args => {
        getAllMenu({ current: currentRef.current, pageSize: pageSizeRef.current, ...args }).then(res => {
            if (res.code === 200) {
                setAllMenu(res.data);
                setTotal(res.total);
            }
        });
    };
    const formatMenu = data => {
        return data.map(item => {
            if (item.children) {
                return {
                    ...item,
                    value: item._id,
                    key: item._id,
                    title: (
                        <Fragment>
                            {myIcons[item.icon]}&nbsp;{item.title}
                        </Fragment>
                    ),
                    children: [...formatMenu(item.children)],
                };
            } else {
                return {
                    ...item,
                    key: item._id,
                    value: item._id,
                    title: (
                        <Fragment>
                            {myIcons[item.icon]}&nbsp;{item.title}
                        </Fragment>
                    ),
                };
            }
        });
    };
    const addMenuKey = data => {
        return data.map(item => {
            if (item.children) {
                return {
                    ...item,
                    key: item._id,
                    children: [...addMenuKey(item.children)],
                };
            } else {
                return {
                    ...item,
                    key: item._id,
                };
            }
        });
    };
    return (
        <>
            <div className="mb-10">
                <Button
                    type="primary"
                    onClick={() => {
                        isAddRef.current = true;
                        setIsAdd(true);
                        setAddModalVisible(true);
                        setTimeout(() => {
                            menuFormRef.current.resetFields();
                        });
                    }}
                >
                    添加菜单
                </Button>
            </div>
            <Table
                scroll={{
                    x: columns.reduce((pre, item) => {
                        return (pre.width ? pre.width : pre) + (item.width ? item.width : 0);
                    }),
                    y: 600,
                }}
                columns={columns}
                dataSource={addMenuKey(allMenu)}
                pagination={{
                    total,
                    current,
                    pageSize,
                    onChange: (current, pageSize) => {
                        setCurrent(current);
                        currentRef.current = current;
                        setPageSize(pageSize);
                        pageSizeRef.current = pageSize;
                        getAllMenu_com({ current, pageSize });
                    },
                }}
            />
            <Modal
                title={`添加/修改菜单`}
                visible={addModalVisible}
                cancelText="取消"
                okText="确认"
                onOk={() => {
                    menuFormRef.current.validateFields().then(formData => {
                        if (isAddRef.current) {
                            addMenu(formData).then(res => {
                                if (res.code == 200) {
                                    message.success("添加成功");
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 1000);
                                } else {
                                    message.error(res.message);
                                }
                            });
                        } else {
                            formData._id = editIdRef.current;
                            updateMenu(formData).then(res => {
                                if (res.code == 200) {
                                    message.success("修改成功");
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 1000);
                                } else {
                                    message.error(res.message);
                                }
                            });
                        }
                    });
                }}
                onCancel={() => setAddModalVisible(false)}
                keyboard={true}
            >
                <Form ref={menuFormRef} wrapperCol={{ span: 12 }} labelCol={{ span: 7 }}>
                    {isAdd ? (
                        <Form.Item label="父菜单" name="parentId">
                            <TreeSelect treeData={formatMenu(allMenu)} />
                        </Form.Item>
                    ) : (
                        <></>
                    )}
                    <Form.Item name="title" label="菜单名" rules={[{ required: true, message: "菜单名不能为空" }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="path" label="路径" rules={[{ required: true, message: "路径不能为空" }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="icon" label="菜单图标">
                        <Select>
                            <Option value="" key="" />
                            {Object.entries(myIcons).map((item, index) => (
                                <Option value={item[0]} key={index}>
                                    {item[1]}&nbsp;{item[0]}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};
